import {loginByUsername, logout, getUserInfo} from '@/api/login'
import {getToken, setToken, removeToken} from '@/utils/auth'
import store from "../index";
import router from "../../router";

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({commit}, userInfo) {
      const mobile = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(mobile, userInfo.password).then(response => {
          const res = response.data;
          //console.log(res);
          if (200 === res.code) {
            
            const rolesData = res.data.role;
            let roles = ['user'];
            if (rolesData.admin) {
              roles.push('admin');
            }
            if (rolesData.dealer) {
              roles.push('dealer');
            }
            if (rolesData.issue) {
              roles.push('issue');
            }
            if (rolesData.market) {
              roles.push('market');
            }
            //console.log(roles);
            localStorage.setItem('roles',JSON.stringify(roles));
            localStorage.setItem('userName',res.data.name);
            localStorage.setItem('userId',res.data.id);
            if (roles && roles.length > 1) { // 验证返回的roles是否是一个非空数组
              commit('SET_NAME', res.data.name);
              commit('SET_ROLES', roles);
              commit('SET_AVATAR', res.data.avatar ? res.data.avatar : 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
              localStorage.setItem('id', res.data.id);
              // commit('SET_INTRODUCTION', res.data.introduction)
              setToken(res.data.token)
              store.dispatch('GenerateRoutes', {roles}).then(() => { // 根据roles权限生成可访问的路由表
                router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                //next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
              })
              resolve()
            } else {
              alert('请在App端登录账号!');
              return false;
            }
            
          } else {
            reject(res)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息 你们不用这个吗
    GetUserInfo({commit, state}) {
      console.log('getUserInfo')
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('error')
          }
          const data = response.data;
          let roles = ['user'];
          if (data.data.role.admin) {
            roles.push('admin');
          }
          if (data.data.role.dealer) {
            roles.push('dealer');
          }
          if (data.data.role.issue) {
            roles.push('issue');
          }
          if (data.data.role.market) {
            roles.push('market');
          }
          if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_NAME', data.data.name);
            commit('SET_ROLES', roles);
            commit('SET_AVATAR', data.data.avatar ? data.data.avatar : 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          // commit('SET_INTRODUCTION', data.data.introduction)
          response.data.roles = roles;
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
          localStorage.removeItem('roles');
          localStorage.removeItem('userName');
          localStorage.removeItem('userId');
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({commit, dispatch}, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
          resolve()
        })
      })
    }
  }
}

export default user
